<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */

use App\Classes\DataRelease\DataRelease;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Asset\Video\Vseriali;
use App\Models\Entity\Asset\Vlive\Vchan;
use App\Models\Entity\Column\Album;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\CollistColumn;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\Recommend;
use App\Models\Entity\Column\Subcolumn;
use App\Models\Entity\Column\SubcolumnVasseti;
use App\Models\Entity\Column\SubcolumnVchan;
use App\Models\Operation\OperationTemplateData;
use App\Models\Operation\TemplateAreaData;
use App\Models\Operation\TemplateSubcolumnVassetiData;
use App\Models\Injection\InjectAssetiHistory;
use App\Models\Entity\Assets\Assets;
use App\Models\Entity\Assets\AssetStream;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Noodlehaus\Config;

// 根路径
Route::get('/', function () {
    return redirect()->to('admin');
});

// 媒资异步注入回调【消息任务处理异步反馈 和 注入CDN成功异步反馈】
Route::any('/vassetis/injection/callback', function (Request $request) {
    // 接收回调的soap消息
    $xmlData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
    if (empty($xmlData)) {
        $xmlData = file_get_contents('php://input', true);
    }
    // Log::info($xmlData);
    $xmlData = str_ireplace("soapenv:", "", $xmlData);
    $xmlData = str_ireplace("ns1:", "", $xmlData);
    // 将xml转化为json对象
    $message = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
    if ($message) {
        // xml数据转json
        $result = json_encode($message);
        // json转数组
        $aResult = json_decode($result, true);
        // 判断媒资id是否存在
        if (isset($aResult['Body']['ResultNotify']['CorrelateID'])) {
            $correlateID = $aResult['Body']['ResultNotify']['CorrelateID'];
        }
        // 判断是否为注入CDN异步反馈
        if (isset($aResult['Body']) && isset($aResult['Body']['multiRef']) && $aResult['Body']['multiRef'] == 0) {
            if (substr($correlateID, 0, 1) === 'j') {
                $id = substr($correlateID, strrpos($correlateID, '|') + 1);
                Vasseti::where('id', '=', $id)->update(['async_content' => $result, 'async_result' => 1]);
            } else {
                Vseriali::where('id', '=', $id)->update(['async_content' => $result, 'async_result' => 1]);
            }
            // 将注入反馈以数组的方式记录在日志
            $resultContent = array('结果(-1:失败,0:成功)' => $aResult['Body']['multiRef'], '媒资id(|符号后面是媒资id)' => $correlateID);
            Log::info($resultContent);
        } else {
            // 失败原因去回调回来的'ResultFileURL'地址中的xml文件中获取
            $description = file_get_contents($aResult['Body']['ResultNotify']['ResultFileURL'], true);
            $description = simplexml_load_string($description, 'SimpleXMLElement', LIBXML_NOCDATA);
            $result2     = json_encode($description);
            $result1     = json_decode($result2, true);
            $errorResult = $result1['Reply']['Property'][1];
            // 将注入反馈以数组的方式记录在日志
            $resultContent = array('结果(-1:失败,0:成功)' => $aResult['Body']['multiRef'], '媒资id(|符号后面是媒资id)' => $correlateID, '失败原因' => $errorResult);
            Log::info($resultContent);
        }
    }
});

// 注入
Route::get('/vassetis/injection', function () {
    /**
     *
     * 内容下发
     * 消息方向:CSP->LSP, LSP以 `cmspost` 接受XML指令
     * 通知响应: Result:0成功, -1 失败; ErrorDescription:错误信息详细描述
     * 下游接受消息, 并同步反馈接受结果
     */
    $time = udate('YmdHisu');
    // $msg_id = $time . uniqid();
    $msg_id = 'j' . $time . uniqid() . 2;
    Vasseti::where('id', '=', 2)->update(['msg_id' => $msg_id]);

    // cpid
    // $cp_id    = $config_media_injection_cp_id;
    // CSPID
    $csp_id = config('custom.base.media_injection.csp_id');
    // LSPID
    $lsp_id = config('custom.base.media_injection.lsp_id');
    // 注入调用的地址
    // $url = 'http://192.168.13.141:35100/cms/services/ctms';
    // xmld地址
    // $file_url = 'ftp://web1:123456@10.69.42.148/upload/xml/3.xml';
    $file_url = 'ftp://ftptest:12345678@192.168.18.150:21/upload/xml/vassetis2.xml';
    // 定义content-type为xml
    // $header[] = "Content-Type: application/soap+xml";
    $arr_header[] = "Content-type: text/xml; charset=utf-8";
    // $arr_header[] = "Content-Type: application/soap+xml; charset=utf-8";
    $arr_header[] = "SOAPAction:\"\"";
    // 构造xml
    /*$post_data = '<?xml version="1.0" encoding="UTF-8"?>';*/
    // $data = [];
    //
    // $post_data = '';
    $post_data = '<?xml version="1.0" encoding="UTF-8"?>';
    $post_data .= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
    $post_data .= '<soapenv:Body>';
    $post_data .= '<ns1:ExecCmd xmlns:ns1="iptv" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">';
    $post_data .= '<CSPID xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">' . $csp_id . '</CSPID>';
    $post_data .= '<LSPID xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">' . $lsp_id . '</LSPID>';
    $post_data .= '<CorrelateID xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">' . $msg_id . '</CorrelateID>';
    $post_data .= '<CmdFileURL xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">' . $file_url . '</CmdFileURL>';
    $post_data .= '</ns1:ExecCmd>';
    $post_data .= '</soapenv:Body>';
    $post_data .= '</soapenv:Envelope>';
    // 注入调用的地址
    // $url = "http://10.21.1.16/nn_gzgdbk/api_v2/import/http_import.php";
    $url = "http://192.168.13.141:35100/cms/services/ctms";
    //首先检测是否支持curl
    if (!extension_loaded("curl")) {
        trigger_error("对不起，请开启curl功能模块！", E_USER_ERROR);
    }
    // 初始一个curl会话
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
    // 设置url
    curl_setopt($ch, CURLOPT_URL, $url);
    // TRUE, 将curl_exec()获取的信息以字符串返回, 而不是直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 设置发送方式:post
    curl_setopt($ch, CURLOPT_POST, 1);
    // 设置发送数据
    // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    // 执行cURL会话
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);
    // post的数据为xml字符串，通过 $xml = simplexml_load_string($post_data);转换成xml对象
    $xml = str_ireplace("soapenv:", "", $response);
    $xml = str_ireplace("ns1:", "", $xml);
    $xml = simplexml_load_string($xml);
    dump($xml);
    //先把xml转换为simplexml对象，再把simplexml对象转换成 json，再将 json 转换成数组。
    // $value_array = json_decode(json_encode(simplexml_load_string($return_xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    echo "<h3>接收到的值</h3>";
    // 将xml对象转为json
    $res = json_decode(json_encode($xml), true);
    dump($res);
    if (isset($res['Body']['ExecCmdResponse']['ExecCmdReturn']['ErrorDescription'])) {
        $errorDescription = $res['Body']['ExecCmdResponse']['ExecCmdReturn']['ErrorDescription'];
        dump($errorDescription);
    }
    die();
});

// 视频列表
Route::get('/videos', function (Request $request) {
    $q                  = $request->input('q');
    $skip               = $request->input('page', 1);
    $limit              = $request->input('limit', 30);
    $skip               = ($skip - 1) * $limit;
    $total_count        = DB::table('recommended_video')->where('title', 'like', '%' . $q . '%')->count();
    $results            = DB::table('recommended_video')->select(["id", "vid", "linkurl", "imgurl", "title", "subtitle", "description"])->where('title', 'like', '%' . $q . '%')->skip($skip)->take($limit)->get()->toArray();
    $incomplete_results = false;
    return response()->json(["total_count" => $total_count, "results" => $results, "incomplete_results" => $incomplete_results]);
});

// 保存推介位数据
Route::post('/save', function (Request $request) {
    $start_time    = $request->input('start_time');
    $end_time      = $request->input('end_time');
    $content       = json_encode($request->input('content'));
    $template_type = $request->input('template_type');
    $template_no   = $request->input('template_no');

    $item                = new OperationTemplateData();
    $item->start_time    = $start_time;
    $item->end_time      = $end_time;
    $item->content       = $content;
    $item->template_type = $template_type;
    $item->template_no   = $template_no;
    if ($item->save()) {
        return response()->json(["content" => "保存成功!", "status" => "success"]);
    } else {
        return response()->json(["content" => "保存失败!", "status" => "error"]);
    }

});

// GET http://[host]:[port]/data/{templtype}/{templid}/{spid}/{chanid}/{term}/{midware}/{datetime}/
// 获得推介位数据
Route::any('/data/{templtype}/{templid}/{spid?}/{chanid?}/{term?}/{midware?}/{datetime?}', function (Request $request) {
    $template_type = $request->route('templtype');
    $template_no   = $request->route('templid');
    $datetime      = $request->route('datetime');
    if (!$datetime) {
        $datetime = Carbon::now();
    } else {
        $datetime = Carbon::parse($datetime);
    }
    // echo strtotime(date('Y-m-d 00:00:00'));  //当日之初
    // echo strtotime(date('Y-m-d 23:59:59')); //当日之末

    // $start_time = strtotime($datetime);
    // $end_tiem = strtotime($datetime) + 24*3600-1;

    $content = OperationTemplateData::where(["template_type" => $template_type, "template_no" => $template_no])->where('start_time', '<=', $datetime)->where('end_time', '>=', $datetime)->first();
    return response()->json(["content" => $content, "status" => "success"]);

});

// 专题
Route::post('/template_type/data/subjects', function (Request $request) {
    if ($request->ajax()) {
        $data                 = array();
        $data['draw']         = $request->get('draw');
        $start                = $request->get('start') ?: 0;
        $length               = $request->get('length') ?: 10;
        $order                = $request->get('order');
        $columns              = $request->get('columns');
        $search               = $request->get('search');
        $data['recordsTotal'] = Album::onlineStatus()->onlinePublished()->count();
        $search_value         = $request->input('search_value');
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = Album::onlineStatus()->onlinePublished()
            ->with(['cols', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->count();
        $data['data'] = Album::onlineStatus()->onlinePublished()
            ->with(['cols', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();

        return response()->json($data);
    }
    return;
});

// 推荐位
Route::post('/template_type/data/recommends', function (Request $request) {
    if ($request->ajax()) {
        $data                 = array();
        $data['draw']         = $request->get('draw');
        $start                = $request->get('start') ?: 0;
        $length               = $request->get('length') ?: 10;
        $order                = $request->get('order');
        $columns              = $request->get('columns');
        $search               = $request->get('search');
        $data['recordsTotal'] = Recommend::onlineStatus()->onlinePublished()->count();
        $search_value         = $request->input('search_value');
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }

        $data['recordsFiltered'] = Recommend::onlineStatus()->onlinePublished()
            ->with(['collist', 'column', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%');
                }
            })->count();
        $data['data'] = Recommend::onlineStatus()->onlinePublished()
            ->with(['collist', 'column', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%');
                }
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }
    return;
});

// 点播媒资
Route::post('/template_type/data/points', function (Request $request) {
    if ($request->ajax()) {
        // 归类
        $vcat = $request->input('vcat');
        // 分类
        $vcattag = $request->input('vcattag');
        // 搜索框的值
        $search_value = $request->input('search_value');

        $data         = array();
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        // TODO根据上线状态条件
        $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->count();
        $search_value         = $request->input('search_value');
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = Vasseti::onlineStatus()->onlinePublished()
            ->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->whereHas('vcat', function ($query) use ($vcat) {
                if (!empty($vcat)) {
                    $query = $query->where('id', $vcat);
                }
            })
            ->whereHas('vcattags', function ($query) use ($vcattag) {
                if (!empty($vcattag)) {
                    $query = $query->where('vcattag_id', $vcattag);
                }
            })
            ->count();

        $data['data'] = Vasseti::OnlineStatus()->OnlinePublished()
            ->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->whereHas('vcat', function ($query) use ($vcat) {
                if (!empty($vcat)) {
                    $query = $query->where('id', $vcat);
                }
            })
            ->whereHas('vcattags', function ($query) use ($vcattag) {
                if (!empty($vcattag)) {
                    $query = $query->where('vcattag_id', $vcattag);
                }
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();

        return response()->json($data);
    }
    return;
});

// 栏目列表
Route::post('/template_type/data/collists', function (Request $request) {
    if ($request->ajax()) {
        $collist_id = $request->input('collist');
        // 搜索框的值
        $search_value = $request->input('search_value');
        $data         = array();
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        // $data['recordsTotal'] = Collist::count();
        $data['recordsTotal'] = CollistColumn::whereHas('cols', function ($query) {
            $query = $query->onlineStatus()->onlinePublished();
        })
            ->whereHas('collist', function ($query) {
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->count();
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }

        $data['recordsFiltered'] = CollistColumn::with(['cols', 'collist'])
            ->whereHas('cols', function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orwhere('short_desc', 'like', '%' . $search_value . '%');
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->whereHas('collist', function ($query) use ($collist_id) {
                if (!empty($collist_id)) {
                    $query = $query->where('id', '=', $collist_id);
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->count();

        $data['data'] = CollistColumn::with(['cols', 'collist'])
            ->whereHas('cols', function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orwhere('short_desc', 'like', '%' . $search_value . '%');
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->whereHas('collist', function ($query) use ($collist_id) {
                if (!empty($collist_id)) {
                    $query = $query->where('id', '=', $collist_id);
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }
    return;
});

// 直播媒资
Route::post('/template_type/data/lives', function (Request $request) {
    if ($request->ajax()) {
        // 归类
        $vccat = $request->input('vccat');
        // 分类
        $vccattag = $request->input('vccattag');
        // 搜索框的值
        $search_value = $request->input('search_value');

        $data                 = array();
        $data['draw']         = $request->get('draw');
        $start                = $request->get('start') ?: 0;
        $length               = $request->get('length') ?: 10;
        $order                = $request->get('order');
        $columns              = $request->get('columns');
        $search               = $request->get('search');
        $data['recordsTotal'] = Vchan::onlineStatus()->onlinePublished()->count();
        $search_value         = $request->input('search_value');
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = Vchan::onlineStatus()->onlinePublished()
            ->with(['vccat', 'vlangs', 'vcareacats', 'vccattags'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->whereHas('vccat', function ($query) use ($vccat) {
                if (!empty($vccat)) {
                    $query = $query->where('id', $vccat);
                }
            })
            ->whereHas('vccattags', function ($query) use ($vccattag) {
                if (!empty($vccattag)) {
                    $query = $query->where('vccat_id', $vccattag);
                }
            })
            ->count();

        $data['data'] = Vchan::onlineStatus()->onlinePublished()
            ->with(['vccat', 'vlangs', 'vcareacats', 'vccattags'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->whereHas('vccat', function ($query) use ($vccat) {
                if (!empty($vccat)) {
                    $query = $query->where('id', $vccat);
                }
            })
            ->whereHas('vccattags', function ($query) use ($vccattag) {
                if (!empty($vccattag)) {
                    $query = $query->where('vccat_id', $vccattag);
                }
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }
    return;
});

/**
 *  区位模板五数据保存
 */
Route::any("template_type/data/subcolumn/save", function (Request $request) {

    // 当栏目为区位模板五的话栏目ID和二级栏目ID都不能为空
    $template_type = $request->input('template_type');
    $template_no   = $request->input('template_no');
    $resource_type = $request->input('resource_type');
    $area_no       = $request->input('area_no');
    $resource_id   = $request->input('resource_id');
    $start_time    = $request->input('start_time');
    $end_time      = $request->input('end_time');
    $home_type     = $request->input('home_type');
    // 栏目列表时获取栏目列表ID以及选择的栏目ID
    $collist_id   = $request->input('collist_id');
    $column_id    = $request->input('column_id');
    $subcolumn_id = $request->input('subcolumn_id');
    // 媒资ID
    $vasseti_id = $request->input('vasseti_id');
    // 模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');

    // 资源类型 type:1:点播 2直播
    $type = $request->input('type') ? $request->input('type') : 1;
    // if (empty($type)) {
    //     return response()->json(['status' => 'error', 'content' => '资源类型不能为空!']);
    // }
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID不能为空!']);
    }

    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型为空!']);
    }
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号为空!']);
    }
    if (empty($resource_type)) {
        return response()->json(['status' => 'error', 'content' => '资源类型为空!']);
    }
    if (empty($area_no)) {
        return response()->json(['status' => 'error', 'content' => '区位编号为空!']);
    }
    if (empty($home_type)) {
        return response()->json(['status' => 'error', 'content' => '首页类型为空!']);
    }
    if (empty($collist_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目列表不能为空!']);
    }
    if (empty($column_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目ID为空!']);
    }
    if (empty($subcolumn_id)) {
        return response()->json(['status' => 'error', 'content' => '二级栏目列表栏目ID为空!']);
    }
    if (empty($vasseti_id)) {
        return response()->json(['status' => 'error', 'content' => '媒资为空!']);
    }

    $templateAreaDta = TemplateAreaData::where(['template_type' => $template_type, 'template_no' => $template_no, 'area_no' => $area_no, 'collist_id' => $collist_id, 'column_id' => $column_id, 'subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id])->first();
    // 该区位模板数据库是否存在
    if ($templateAreaDta) {
        // 区位编号为AREA005x1x0y0,或者是Area005x0y1先对已有媒资进行删除
        if ($area_no == 'AREA005x1x0y0' || $area_no == 'AREA005x1x0y1') {
            TemplateSubcolumnVassetiData::where(['area_no' => $area_no, 'subcolumn_id' => $templateAreaDta->subcolumn_id, 'template_details_id' => $template_details_id])->delete();
        }
        // 判断上传的媒资id是一个还是多个
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $key => $value) {
                $flag = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $value['id'], 'template_details_id' => $template_details_id, 'type' => $type])->first();
                if ($flag) {
                    return response()->json(['status' => 'error', 'content' => '不能重复添加已经存在的媒资!']);
                } else {
                    // 取出最新上传的媒资文件
                    $templateSubcolumnVassetiData = new TemplateSubcolumnVassetiData;
                    // 区位编号
                    $templateSubcolumnVassetiData->area_no = $area_no;
                    // 二级栏目列表ID
                    $templateSubcolumnVassetiData->subcolumn_id = $subcolumn_id;
                    // 区位媒资ID
                    $templateSubcolumnVassetiData->vasseti_id          = $value['id'];
                    $templateSubcolumnVassetiData->template_details_id = $template_details_id;

                    // 区位模板类型 2018/1/4
                    $templateSubcolumnVassetiData->type = $type;
                    $storeVassetiStatus                 = $templateSubcolumnVassetiData->save();
                    if (!$storeVassetiStatus) {
                        return response()->json(['status' => 'error', 'content' => '媒资数据保存失败!']);
                    }
                }
            }
            return response()->json(['status' => 'success', 'content' => '媒资保存成功!']);
        } else {
            $flag = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $vasseti_id, 'template_details_id' => $template_details_id, 'type' => $type])->first();
            if ($flag) {
                return response()->json(['status' => 'error', 'content' => '不能重复添加已经存在的媒资!']);
            } else {
                // 取出最新上传的媒资文件
                $templateSubcolumnVassetiData = new TemplateSubcolumnVassetiData;
                // 区位编号
                $templateSubcolumnVassetiData->area_no = $area_no;
                // 二级栏目列表ID
                $templateSubcolumnVassetiData->subcolumn_id = $subcolumn_id;
                // 区位媒资ID
                $templateSubcolumnVassetiData->vasseti_id          = $vasseti_id;
                $templateSubcolumnVassetiData->template_details_id = $template_details_id;
                // 区位模板类型 2018/1/4
                $templateSubcolumnVassetiData->type = $type;
                $storeVassetiStatus                 = $templateSubcolumnVassetiData->save();
                if (!$storeVassetiStatus) {
                    return response()->json(['status' => 'error', 'content' => '媒资数据保存失败!']);
                }
                return response()->json(['status' => 'success', 'content' => '媒资保存成功!']);
            }
        }
    } else {
        // 区位模板内容
        $templateData = new TemplateAreaData;
        // 模板类型, 例如:AREA
        $templateData->template_type = $template_type;
        // 模板编号, 例子:001
        $templateData->template_no = $template_no;
        // 资源类型, 1 => 直播, 2 => 专题，3 => 推荐位，4=>点播媒资 5=>栏目列表
        $templateData->resource_type = $resource_type;
        // 区位编号, 例如: AREA001x1x0y0
        $templateData->area_no = $area_no;

        // 区位模板所属首页类型  首页 直播首页 点播首页 回看首页
        $templateData->home_type = $home_type;
        // 栏目列表Id
        $templateData->collist_id = $collist_id;
        // 栏目Id
        $templateData->column_id = $column_id;
        // 二级栏目列表ID
        $templateData->subcolumn_id = $subcolumn_id;
        // 详情ID
        $templateData->template_details_id = $template_details_id;
        $savetemplateDataStatus            = $templateData->save();
        if (!$savetemplateDataStatus) {
            return response()->json(['status' => 'error', 'content' => '区位模板数据保存失败!']);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $vassetiIdkey => $vassetiIdValue) {
                $flag = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $vassetiIdValue['id'], 'template_details_id' => $template_details_id])->first();
                if ($flag) {
                    return response()->json(['status' => 'error', 'content' => '不能重复添加已经存在的媒资!']);
                } else {
                    // 取出最新上传的媒资文件
                    $templateSubcolumnVassetiData = new TemplateSubcolumnVassetiData;
                    // 二级栏目编号
                    $templateSubcolumnVassetiData->subcolumn_id = $subcolumn_id;
                    // 区位编号
                    $templateSubcolumnVassetiData->area_no = $area_no;
                    // 区位媒资ID
                    $templateSubcolumnVassetiData->vasseti_id          = $vassetiIdValue['id'];
                    $templateSubcolumnVassetiData->template_details_id = $template_details_id;
                    // 区位模板类型 2018/1/4 add
                    $templateSubcolumnVassetiData->type = $type;
                    $storeVassetiStatus                 = $templateSubcolumnVassetiData->save();
                    if (!$storeVassetiStatus) {
                        return response()->json(['status' => 'error', 'content' => '媒资数据保存失败!']);
                    }
                }
            }
            return response()->json(['status' => 'success', 'content' => '媒资保存成功!']);
        } else {
            $flag = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $vasseti_id, 'template_details_id' => $template_details_id])->first();
            if ($flag) {
                return response()->json(['status' => 'error', 'content' => '不能重复添加已经存在的媒资!']);
            } else {
                // 取出最新上传的媒资文件
                $templateSubcolumnVassetiData = new TemplateSubcolumnVassetiData;
                // 区位编号
                $templateSubcolumnVassetiData->area_no = $area_no;
                // 二级栏目编号
                $templateSubcolumnVassetiData->subcolumn_id = $subcolumn_id;
                // 区位媒资ID
                $templateSubcolumnVassetiData->vasseti_id          = $vasseti_id;
                $templateSubcolumnVassetiData->template_details_id = $template_details_id;
                // 区位模板类型 2018/1/4
                $templateSubcolumnVassetiData->type = $type;
                $storeVassetiStatus                 = $templateSubcolumnVassetiData->save();
                if (!$storeVassetiStatus) {
                    return response()->json(['status' => 'error', 'content' => '媒资数据保存失败!']);
                }
                return response()->json(['status' => 'success', 'content' => '媒资保存成功!']);
            }
        }
    }
});

/**
 *  区位模板五数据回填
 */
Route::any('/template_type/data/area/subcolumn/backfill', function (Request $request) {

    $template_type = strtolower($request->input('template_type'));
    $template_no   = $request->input('template_no');
    // 根据区位模板栏目列表id,栏目ID,二级栏目列表Id查询相对应媒资资源
    $collist_id   = $request->input('collist_id');
    $column_id    = $request->input('column_id');
    $subcolumn_id = $request->input('subcolumn_id');
    $limit        = $request->input('limit', 6);
    $page         = $request->input('page', 1);

    // 模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID不能为空!']);
    }

    $limit = $page > 1 ? 12 : 6;
    $skip  = $page > 1 ? (($page - 1) * $limit) - 6 : 0;
    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型不能为空!']);
    }
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号不能为空!']);
    }
    if (empty($collist_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目列表不能为空!']);
    }
    if (empty($column_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目ID为空!']);
    }
    if (empty($subcolumn_id)) {
        return response()->json(['status' => 'error', 'content' => '二级栏目列表栏目ID为空!']);
    }
    $templateAreaData = TemplateAreaData::select('area_no')
        ->where([
            'template_no'         => $template_no,
            'template_type'       => $template_type,
            'collist_id'          => $collist_id,
            'column_id'           => $column_id,
            'subcolumn_id'        => $subcolumn_id,
            'template_details_id' => $template_details_id,
        ])
        ->groupBy('area_no')
        ->get();
    if (empty($templateAreaData->first())) {
        return response()->json(['status' => 'error', 'content' => '没有相关区位模板信息!']);
    }
    $total                 = 1;
    $data                  = [];
    $data['template_type'] = $template_type;
    $data['template_no']   = $template_no;
    $data['collist_id']    = $collist_id;
    $data['column_id']     = $column_id;
    $data['subcolumn_id']  = $subcolumn_id;
    $vassetiData           = [];
    $arrVasseti            = [];
    // 图片
    $uploadConfig = config('custom.base.upload.area');
    // driver
    $driver      = $uploadConfig['driver'];
    $uploadHosts = config('custom.base.host');
    $host        = $uploadHosts[$driver];

    foreach ($templateAreaData as $templateAreaDataKey => $templateAreaDataValue) {
        // 根据相关模板的编号取出对应的模板信息 TODO
        if ($templateAreaDataValue->area_no == 'AREA005x1x1') {
            // 取出此二级栏目下面全部的媒资
            $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::
                where(['subcolumn_id' => $subcolumn_id, 'area_no' => $templateAreaDataValue->area_no, 'template_details_id' => $template_details_id])
                ->skip($skip)
                ->take($limit)
                ->orderBy('created_at', 'desc')
                ->select(['vasseti_id', 'type'])
                ->get();
            // ->pluck('vasseti_id');
        } else {
            // 否则取出此二级栏目下面全部的媒资
            $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::where([
                'subcolumn_id'        => $subcolumn_id,
                'area_no'             => $templateAreaDataValue->area_no,
                'template_details_id' => $template_details_id,
            ])
                ->select(['vasseti_id', 'type'])
                ->get();
            // ->pluck('vasseti_id');
        }

        if ($templateSubcolumnVassetiData->first()) {
            // 根据获取的媒资Id获取相应媒资数据
            foreach ($templateSubcolumnVassetiData as $vassetiKey => $vassetiValue) {
                if ($vassetiValue->type == 1) {
                    $vasseti = Vasseti::with(['vposteris'])->where(['id' => $vassetiValue->vasseti_id])->first();
                    if (!empty($vasseti)) {
                        // 区位模板005匹配大图
                        $vassetiData['img'] = '';
                        if ($templateAreaDataValue->area_no == 'AREA005x1x0y0') {
                            // 当期区位图片媒资的具体信息
                            $img = DB::table('template_area_images')->where(['area_no' => $templateAreaDataValue->area_no, 'template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id])->whereNull('deleted_at')->first();
                            if (!empty($img)) {
                                $vassetiData['img'] = $host . $img->img;
                            }
                        } else {
                            $images = $vasseti->vposteris->pluck('href');
                            if (!empty($images)) {
                                foreach ($images as $key => $value) {
                                    if (preg_match('/.*?@(SIMG|simg)\.(jpg|jpeg|png|gif)$/', $value)) {
                                        $vassetiData['img'] = $host . $value;
                                        break;
                                    }
                                }
                            }
                        }
                        $vassetiData['id']         = $vasseti->id;
                        $vassetiData['title']      = $vasseti->title;
                        $vassetiData['vasseti_no'] = $vasseti->vasseti_no;
                        $vassetiData['name']       = $vasseti->name;
                        $vassetiData['subtitle']   = $vasseti->subtitle;
                    } else {
                        $vassetiData['id']         = $vassetiValue->vasseti_id;
                        $vassetiData['title']      = '';
                        $vassetiData['vasseti_no'] = '';
                        $vassetiData['name']       = '';
                        $vassetiData['subtitle']   = '';
                        $vassetiData['img']        = '';
                    }
                    $vassetiData['type'] = 1;
                } else if ($vassetiValue->type == 2) {
                    $vchan = Vchan::with(['vcposters'])->where(['id' => $vassetiValue->vasseti_id])->first();
                    if (!empty($vchan)) {
                        // 区位模板005匹配大图
                        $vassetiData['img'] = '';
                        if ($templateAreaDataValue->area_no == 'AREA005x1x0y0') {
                            // 当期区位图片媒资的具体信息
                            $img = DB::table('template_area_images')->where(['area_no' => $templateAreaDataValue->area_no, 'template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id])->whereNull('deleted_at')->first();
                            if (!empty($img)) {
                                $vassetiData['img'] = $host . $img->img;
                            }
                        } else {
                            $images = $vchan->vcposters->pluck('cposter_url');
                            if (!empty($images)) {
                                foreach ($images as $key => $value) {
                                    if (preg_match('/.*?@(SIMG|simg)\.(jpg|jpeg|png|gif)$/', $value)) {
                                        $vassetiData['img'] = $host . $value;
                                        break;
                                    }
                                }
                            }
                        }
                        $vassetiData['id']         = $vchan->id;
                        $vassetiData['title']      = $vchan->title;
                        $vassetiData['vasseti_no'] = $vchan->vchan_no;
                        $vassetiData['name']       = $vchan->name;
                        $vassetiData['subtitle']   = $vchan->subtitle;
                    } else {
                        $vassetiData['id']         = $vassetiValue->vasseti_id;
                        $vassetiData['title']      = '';
                        $vassetiData['vasseti_no'] = '';
                        $vassetiData['name']       = '';
                        $vassetiData['subtitle']   = '';
                        $vassetiData['img']        = '';
                    }
                    $vassetiData['type'] = 2;
                }
                $arrVasseti[] = $vassetiData;
            }
            // 第一页6条,之后都是12条
            $total = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'area_no' => "AREA005x1x1", 'template_details_id' => $template_details_id])->count();

            // 第一页
            if ($total > 6) {
                $total = ceil(($total - 6) / 12);
                $total += 1;
            } else {
                $total = 1;
            }
        }
        $data['template_datas'][$templateAreaDataValue->area_no] = $arrVasseti;
        $arrVasseti                                              = [];
    }

    $data['total'] = $total;
    return response()->json(['status' => 'success', 'content' => $data]);
});

/*
 * 区位模板五删除数据
 */
Route::post('/template_type/data/area/subcolumn/delete', function (Request $request) {

    $template_type = $request->input('template_type');
    $template_no   = $request->input('template_no');
    // 根据区位模板栏目列表id,栏目ID,二级栏目列表Id查询相对应媒资资源
    $area_no      = $request->input('area_no');
    $collist_id   = $request->input('collist_id');
    $column_id    = $request->input('column_id');
    $subcolumn_id = $request->input('subcolumn_id');
    $vasseti_id   = $request->input('vasseti_id');
    $type         = $request->input('type') ? $request->input('type') : 1;
    // if (empty($type)) {
    //     return response()->json(['status' => 'error', 'content' => '资源类型不能为空!!']);
    // }
    // 模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID不能为空!']);
    }

    if (empty($area_no)) {
        return response()->json(['status' => 'error', 'content' => '区位编号为空!']);
    }
    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型为空!']);
    }
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号为空!']);
    }
    if (empty($collist_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目列表为空!']);
    }
    if (empty($column_id)) {
        return response()->json(['status' => 'error', 'content' => '栏目ID为空!']);
    }
    if (empty($subcolumn_id)) {
        return response()->json(['status' => 'error', 'content' => '二级栏目列表栏目ID为空!']);
    }
    // 查询对应的数据
    $templateAreaData = TemplateAreaData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id])->first();
    if (!$templateAreaData) {
        return response()->json(['status' => 'error', 'content' => '没有相关栏目列表信息!']);
    }
    // 区位编号为area_no为AREA005x1x0y0,则删除对应的区位模板信息以及对应媒资信息

    if ($area_no == 'AREA005x1x0y0') {
        $flag = TemplateAreaData::where(['subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'template_details_id' => $template_details_id])->delete();
        if ($flag) {
            // 判断媒资ID传递的是数组还是单个媒资
            if (is_array($vasseti_id)) {
                // 删除关联媒资信息
                $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'template_details_id' => $template_details_id, 'type' => $type])->whereIn('vasseti_id', $vasseti_id)->delete();
            } else {
                // 删除关联媒资信息
                $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'vasseti_id' => $vasseti_id, 'template_details_id' => $template_details_id, 'type' => $type])->delete();
            }
            if ($templateSubcolumnVassetiData) {
                return response()->json(['status' => 'success', 'content' => '删除成功!']);
            } else {
                return response()->json(['status' => 'error', 'content' => '删除失败!']);
            }
        } else {
            return response()->json(['status' => 'error', 'content' => '区位模板删除失败!']);
        }
        // 区位编号为area005x0y1,则删除其中一个
    } else if ($area_no == 'AREA005x1x0y1') {
        if (is_array($vasseti_id)) {
            $deleteVassetiStatus = TemplateSubcolumnVassetiData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'type' => $type])->whereIn('vasseti_id', $vasseti_id)->delete();
        } else {
            // 删除关联媒资信息
            $deleteVassetiStatus = TemplateSubcolumnVassetiData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'vasseti_id' => $vasseti_id, 'type' => $type])->delete();
        }
        if ($deleteVassetiStatus) {
            $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id, 'area_no' => $area_no])->get();
            if (empty($templateSubcolumnVassetiData->first())) {
                // 二级栏目下媒资为空,则把区位模板信息也进行删除
                $templateArea = TemplateAreaData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id, 'area_no' => $area_no])->delete();
                if ($templateArea) {
                    return response()->json(['status' => 'success', 'content' => '模板删除成功!']);
                } else {
                    return response()->json(['status' => 'error', 'content' => '模板删除失败!']);
                }
            }
            return response()->json(['status' => 'success', 'content' => '删除成功!']);
        } else {
            return response()->json(['status' => 'error', 'content' => '媒资删除失败!']);
        }
    } else if ($area_no == "AREA005x1x1") {

        if (is_array($vasseti_id)) {
            $deleteVassetiStatus = TemplateSubcolumnVassetiData::where([
                'template_details_id' => $template_details_id,
                'subcolumn_id'        => $subcolumn_id, 'area_no' => $area_no,
            ])
                ->whereIn('vasseti_id', $vasseti_id)
                ->delete();
        } else {
            // 删除关联媒资信息
            $deleteVassetiStatus = TemplateSubcolumnVassetiData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id, 'area_no' => $area_no, 'vasseti_id' => $vasseti_id, 'tyep' => $type])->delete();
        }
        if ($deleteVassetiStatus) {
            $templateSubcolumnVassetiData = TemplateSubcolumnVassetiData::where([
                'template_details_id' => $template_details_id,
                'subcolumn_id'        => $subcolumn_id])
                ->get();

            if ($templateSubcolumnVassetiData->first()) {
                return response()->json(['status' => 'success', 'content' => '删除成功!']);
            } else {
                // 则把区位模板信息也进行删除
                $templateArea = TemplateAreaData::where(['template_details_id' => $template_details_id, 'subcolumn_id' => $subcolumn_id])->delete();
                if ($templateArea) {
                    return response()->json(['status' => 'success', 'content' => '模板删除成功!']);
                } else {
                    return response()->json(['status' => 'error', 'content' => '模板删除失败!']);
                }
                return response()->json(['status' => 'success', 'content' => '删除成功!']);
            }
        } else {
            return response()->json(['status' => 'error', 'content' => '删除失败!']);
        }
    }
});

// 保存区位模板数据
Route::post("/template_type/data/savedata", function (Request $request) {

    $template_type = $request->input('template_type');
    $template_no   = $request->input('template_no');
    $resource_type = $request->input('resource_type');
    $area_no       = $request->input('area_no');
    $resource_id   = $request->input('resource_id');
    $start_time    = $request->input('start_time');
    $end_time      = $request->input('end_time');
    // 首页类型 1-首页 2-直播首页 3-点播首页 4回看首页
    $home_type = $request->input('home_type');
    // 模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID不能为空!']);
    }
    $tag_no = $request->input('tag_no');
    if (empty($tag_no)) {
        return response()->json(['status' => 'error', 'content' => '区位编号不能为空!']);
    }

    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型不能为空!']);
    }
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号不能为空!']);
    }
    if (empty($resource_type)) {
        return response()->json(['status' => 'error', 'content' => '资源类型不能为空!']);
    }
    if (empty($area_no)) {
        return response()->json(['status' => 'error', 'content' => '区位编号不能为空!']);
    }

    if (empty($resource_id)) {
        return response()->json(['status' => 'error', 'content' => '区位资源ID不能为空!']);
    }
    if (empty($home_type)) {
        return response()->json(['status' => 'error', 'content' => '首页类型不能为空!']);
    }

    $template_type = strtolower($template_type);
    // 对区位模板先进行删除
    TemplateAreaData::where(['template_details_id' => $template_details_id, 'template_type' => $template_type, 'template_no' => $template_no, 'area_no' => $area_no, 'tag_no' => $tag_no])->delete();

    foreach ($resource_id as $resource_key => $resource_value) {
        // 区位模板内容
        $templateData = new TemplateAreaData;
        // 模板类型, 例如:AREA
        $templateData->template_type = $template_type;
        // 模板编号, 例子:001
        $templateData->template_no = $template_no;
        // 区位编号
        $templateData->template_details_id = $template_details_id;
        // 模板内容详情
        $templateData->tag_no = $tag_no;
        // 资源类型, 1 => 直播, 2 => 专题，3 => 推荐位，4=>点播媒资 5=>栏目列表
        $templateData->resource_type = $resource_type;
        // 区位编号, 例如: AREA001x1x0y0
        $templateData->area_no = $area_no;
        // 区位文件资源ID
        $templateData->resource_id = $resource_value['id'];
        // 开始时间
        $templateData->start_time = $start_time;
        // 结束时间
        $templateData->end_time = $end_time;
        // 区位模板所属首页类型  首页 直播首页 点播首页 回看首页
        $templateData->home_type = $home_type;
        // 当资源类型为栏目列表时,获取栏目列表ID
        if ($resource_type == 5) {
            if (empty($resource_value['collist_id'])) {
                return response()->json(['status' => 'error', 'content' => '栏目列表ID不能为空!']);
            }
            $templateData->collist_id = $resource_value['collist_id'];
        }
        // 保存数据
        if (!$templateData->save()) {
            return response()->json(['status' => 'error', 'content' => '区位模板数据保存失败!']);
        }
    }
    return response()->json(['status' => 'success', 'content' => '区位模板数据保存成功!']);
});

// 区位模板数据删除
Route::post("/template_type/data/area/delete", function (Request $request) {
    $template_type = $request->input('template_type');
    $template_no   = $request->input('template_no');
    $area_no       = $request->input('area_no');
    // 区位编号
    $tag_no = $request->input('tag_no');
    // 内容模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');
    if (empty($area_no)) {
        return response()->json(['status' => 'error', 'content' => '区位编号为空!']);
    }
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID为空!']);
    }
    // 模板类型
    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型为空!']);
    }
    // 模板编号
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号为空!']);
    }
    // 内容模板
    if (empty($tag_no)) {
        return response()->json(['status' => 'error', 'content' => '区位模板详情编号为空!']);
    }
    // 查询对应的数据
    $templateAreaData = TemplateAreaData::where([
        'template_details_id' => $template_details_id,
        'area_no'             => $area_no,
        'tag_no'              => $tag_no,
    ])->first();
    if (!$templateAreaData) {
        return response()->json(['status' => 'error', 'content' => '没有相关区位列表详情信息!']);
    }

    if (TemplateAreaData::where(['template_details_id' => $template_details_id, 'area_no' => $area_no, 'tag_no' => $tag_no])->delete()) {
        return response()->json(['status' => 'success', 'content' => '删除成功!']);
    } else {
        return response()->json(['status' => 'error', 'content' => '删除失败!']);
    }

});

// 图片以及title信息,获取推荐位信息图片
Route::get("/template_type/data/infos", function (Request $request) {
    // 资源类型
    $resource_type = $request->input('resource_type');
    // 资源id
    $resource_id = $request->input('resource_id');

    if (empty($resource_type)) {
        return response()->json(['status' => 'error', 'content' => '资源类型不能为空!']);
    }
    if (empty($resource_id)) {
        return response()->json(['status' => 'error', 'content' => '区位资源ID不能为空!']);
    }
    $datas = [];
    foreach ($resource_id as $resource_key => $resource_value) {
        switch ($resource_type) {
            // 直播目前使用点播媒资资源
            case 1:
                $list[] = $resource_value;
                $vchan  = Vchan::with(['vccat', 'vlangs', 'vcareacats', 'vccattags'])
                    ->where(['id' => $resource_value['id']])
                    ->first();
                if (!empty($vchan)) {
                    $data['title'] = $vchan->name;
                } else {
                    $data['img']   = '';
                    $data['title'] = '';
                }
                break;
            // 专题
            case 2:
                $album = Album::with(['cols', 'vassetis'])
                    ->where(['id' => $resource_value['id']])
                    ->first();
                if (!empty($album)) {
                    $data['title'] = $album->name;
                } else {
                    $data['img']   = '';
                    $data['title'] = '';
                }
                break;
            // 推荐位
            case 3:
                $recommend = Recommend::with(['collist', 'column', 'vassetis'])
                    ->where(['id' => $resource_value['id']])
                    ->first();
                if (!empty($recommend)) {
                    $data['title'] = $recommend->name;
                } else {
                    $data['img']   = '';
                    $data['title'] = '';
                }
                break;
            // 点播媒资
            case 4:
                $vasseti = Vasseti::with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags', 'vposteris'])
                    ->where(['id' => $resource_value['id']])
                    ->first();
                if (!empty($vasseti)) {
                    $data['title'] = $vasseti->name;
                } else {
                    $data['title'] = '';
                }
                break;
            // 栏目列表
            case 5:
                $column = Column::where(['id' => $resource_value['id']])
                    ->first();
                if (!empty($column)) {
                    $data['title'] = $column->name;
                } else {
                    $data['title'] = '';
                }
                break;
            default:
                $data['title'] = '';
                break;
        }
        $datas[] = $data;
    }
    return response()->json(['status' => 'success', 'content' => $datas]);
});

// 区位模板数据回填数据
Route::get("template_type/data/{template_type}/{template_no}/backfill", function (Request $request, $template_type, $template_no) {
    if (empty($template_type)) {
        return response()->json(['status' => 'error', 'content' => '模板类型不能为空!']);
    }
    if (empty($template_no)) {
        return response()->json(['status' => 'error', 'content' => '模板编号不能为空!']);
    }
    // 模板详情列表ID
    $template_details_id = (int) $request->input('templateDetailsId');
    if (empty($template_details_id)) {
        return response()->json(['status' => 'error', 'content' => '内容模板详情ID不能为空!']);
    }
    $data                  = [];
    $template_type         = strtolower($template_type);
    $data['template_type'] = $template_type;
    $data['template_no']   = $template_no;

    // 资源ID以及资源类型
    $areaNos = TemplateAreaData::
        where(['template_type' => $template_type, 'template_no' => $template_no, 'template_details_id' => $template_details_id])
        ->select(['area_no'])
        ->groupBy('area_no')
        ->get();

    if (!empty($areaNos)) {
        $area  = [];
        $areas = [];
        foreach ($areaNos as $key => $value) {
            // 区位编号取出下面的数据
            $templateAreaData = TemplateAreaData::where(['template_details_id' => $template_details_id, 'area_no' => $value->area_no])->get();
            foreach ($templateAreaData as $templateKey => $templateValue) {
                switch ($templateValue->resource_type) {
                    case '1':
                        $vchan = Vchan::onlineStatus()->onlinePublished()->with(['vccat', 'vlangs', 'vcareacats', 'vccattags'])->where(['id' => $templateValue->resource_id])->first();
                        if (!empty($vchan)) {
                            // 标题
                            $area['title'] = $vchan->title;
                            // 名称
                            $area['name'] = $vchan->name;
                            // 图片

                        } else {
                            $area['title'] = '';
                            $area['name']  = '';
                            $area['img']   = '';
                        }
                        // 资源ID
                        $area['resource_id'] = $templateValue->resource_id;
                        // 资源类型
                        $area['resource_type'] = $templateValue->resource_type;
                        // 区位模板详情编号
                        $area['tag_no'] = $templateValue->tag_no;
                        // 资源类型名称
                        $area['resource_name'] = '直播';
                        break;
                    case '2':
                        $album = Album::onlineStatus()->onlinePublished()->with(['cols', 'vassetis'])->where(['id' => $templateValue->resource_id])->first();
                        if (!empty($album)) {
                            // 标题
                            $area['title'] = $album->title;
                            // 名称
                            $area['name'] = $album->name;
                        } else {
                            $area['title'] = '';
                            $area['name']  = '';
                        }
                        // 资源ID
                        $area['resource_id'] = $templateValue->resource_id;
                        // 资源类型
                        $area['resource_type'] = $templateValue->resource_type;
                        // 区位模板详情编号
                        $area['tag_no'] = $templateValue->tag_no;
                        // 资源类型名称
                        $area['resource_name'] = '专题';
                        break;
                    case '3':
                        $recommend = Recommend::onlineStatus()->onlinePublished()->with(['collist', 'column', 'vassetis'])->where(['id' => $templateValue->resource_id])->first();
                        if (!empty($recommend)) {
                            // 标题
                            $area['title'] = $recommend->title;
                            // 名称
                            $area['name'] = $recommend->name;
                        } else {
                            $area['title'] = '';
                            $area['name']  = '';
                        }
                        // 资源ID
                        $area['resource_id'] = $templateValue->resource_id;
                        // 资源类型
                        $area['resource_type'] = $templateValue->resource_type;
                        // 区位模板详情编号
                        $area['tag_no'] = $templateValue->tag_no;
                        // 资源类型名称
                        $area['resource_name'] = '推荐位';
                        break;
                    case '4':
                        $vasseti = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags', 'vposteris'])->where(['id' => $templateValue->resource_id])->first();

                        if (!empty($vasseti)) {
                            // 标题
                            $area['title'] = $vasseti->title;
                            // name
                            $area['name'] = $vasseti->name;
                        } else {
                            $area['title'] = '';
                            $area['name']  = '';
                            $area['img']   = '';
                        }
                        // 资源ID
                        $area['resource_id'] = $templateValue->resource_id;
                        // 资源类型
                        $area['resource_type'] = $templateValue->resource_type;
                        // 区位模板详情编号
                        $area['tag_no'] = $templateValue->tag_no;
                        // 资源类型名称
                        $area['resource_name'] = '点播';
                        break;
                    case '5':
                        $column = Column::onlineStatus()->onlinePublished()->where(['id' => $templateValue->resource_id])->first();
                        if (!empty($column)) {
                            // 标题
                            $area['title'] = $column->title;
                            // name
                            $area['name'] = $column->name;
                        } else {
                            $area['title'] = '';
                            $area['name']  = '';
                        }
                        // 资源ID
                        $area['resource_id'] = $templateValue->resource_id;
                        // 资源类型
                        $area['resource_type'] = $templateValue->resource_type;
                        // 区位模板详情编号
                        $area['tag_no'] = $templateValue->tag_no;
                        // 资源类型名称
                        $area['resource_name'] = '栏目列表';
                        break;
                }
                // 当期区位图片媒资的具体信息
                $img = DB::table('template_area_images')->where(['area_no' => $value->area_no, 'tag_no' => $templateValue->tag_no, 'template_details_id' => $template_details_id])->whereNull('deleted_at')->first();

                if (!empty($img)) {
                    // 图片
                    $uploadConfig = config('custom.base.upload.area');
                    // driver
                    $driver      = $uploadConfig['driver'];
                    $uploadHosts = config('custom.base.host');
                    $host        = $uploadHosts[$driver];
                    $area['img'] = $host . $img->img;
                } else {
                    $area['img'] = '';
                }
                $areas[] = $area;
            }
            $data['template_datas'][$value->area_no] = $areas;
            $areas                                   = [];
        }
    }
    return response()->json(['status' => 'success', 'content' => $data]);
});

// 保存区位模板数据2
Route::post("/template_type/save", function (Request $request) {
    $content = $request->input('data');
    foreach ($data as $data_key => $data_value) {
        // 区位模板内容
        $templateData = new TemplateAreaData;
        // 模板类型, 例如:AREA
        $templateData->template_type = $data_value['template_type'];
        // 模板编号, 例子:001
        $templateData->template_no = $data_value['template_no'];
        // 资源类型, 1 => 直播, 2 => 专题，3 => 推荐位，4=>点播媒资 5=>栏目列表
        $templateData->resource_type = $data_value['resource_type'];
        // 区位编号, 例如: AREA001x1x0y0
        $templateData->area_no = $data_value['area_no'];
        // 区位文件资源ID
        $templateData->resource_id = $data_value['resource_id'];
        // 开始时间
        $templateData->start_time = $data_value['start_time'];
        // 结束时间
        $templateData->end_time = $data_value['end_time'];
        // 保存数据
        if (!$templateData->save()) {
            return response()->json('区位模板数据保存失败!');
        }
    }
    return response()->json('区位模板数据保存成功!');
});

// 专题数据填充
Route::post("/template_type/data/subject/create", function (Request $request) {
    // 专题模板数据填充,获取所有的专题
    if ($request->ajax()) {
        $data                 = array();
        $data['draw']         = $request->get('draw');
        $start                = $request->get('start') ?: 0;
        $length               = $request->get('length') ?: 10;
        $order                = $request->get('order');
        $columns              = $request->get('columns');
        $search               = $request->get('search');
        $data['recordsTotal'] = Album::onlineStatus()->onlinePublished()->count();
        $search_value         = $request->input('search_value');
        if ($order && isset($order[0]['column'])) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = Album::onlineStatus()->onlinePublished()
            ->with(['cols', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->count();
        $data['data'] = Album::onlineStatus()->onlinePublished()
            ->with(['cols', 'vassetis'])
            ->where(function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();

        return response()->json($data);
    }
    return;
});

// 获取栏目列表接口
Route::get("/collists", function () {
    $collists = Collist::onlineStatus()->onlinePublished()->get(['name', 'id', 'title']);
    return response()->json(['content' => $collists, 'status' => 'success']);
});

// 通过栏目列表获得该栏目列表下的栏目
Route::get("/collists/{collist_id}/columns", function ($collist_id) {
    if (Collist::find($collist_id)) {
        $ids = CollistColumn::where('collist_id', $collist_id)->pluck('column_id')->toArray();
        // $columns = Column::onlineStatus()->onlinePublished()->whereIn('id', $ids)->orderBy('listorder', 'asc')->get(['name', 'id', 'title']);
        $columns = Column::with(['contentTemplate', 'contentTemplate.contentTemplateType'])->onlineStatus()->onlinePublished()->whereIn('id', $ids)->orderBy('listorder', 'asc')->get();
        $data    = [];
        $datas   = [];
        foreach ($columns as $key => $value) {
            $data['name']  = $value->name;
            $data['id']    = $value->id;
            $data['title'] = $value->title;
            // 模板编号
            if (count($value->contentTemplate)) {
                $data['template_no'] = $value->contentTemplate->template_no;
                if (count($value->contentTemplate->contentTemplateType)) {
                    // 模板类型
                    $data['template_type'] = $value->contentTemplate->contentTemplateType->name;
                } else {
                    $data['template_type'] = null;
                }
            } else {
                $data['template_no']   = null;
                $data['template_type'] = null;
            }
            $datas[] = $data;
        }
        return response()->json(['content' => $datas, 'status' => 'success']);
    }
    return response()->json(['content' => "栏目列表参数不合法!", 'status' => 'error']);
});

// 通过栏目获得该栏目下的二级栏目
Route::get("/columns/{column_id}/subcolumns", function ($column_id) {
    if (Column::find($column_id)) {
        $subcolumns = Subcolumn::onlineStatus()->onlinePublished()->where('column_id', $column_id)->get(['name', 'id', 'title']);
        return response()->json(['content' => $subcolumns, 'status' => 'success']);
    }
    return response()->json(['content' => "栏目参数不合法!", 'status' => 'error']);
});

/**
 * 通过二级栏目下的ID该二级栏目下的点播媒资
 */
Route::any("/subcolumns/{subcolumn_id}/vassetis", function ($subcolumn_id, Request $request) {
    if (Subcolumn::find($subcolumn_id)) {

        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // // 二级栏目id
            $subcolumn_id = $request->input('subcolumn');
            // 模板相关的ID
            $template_details_id = $request->input('templateDetailsId');
            // 类型 : 1-点播 2-直播
            $type                 = 1;
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = SubcolumnVasseti::whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
                if (!empty($subcolumn_id) && !empty($template_details_id)) {
                    $query = $query->where('id', '=', $subcolumn_id);
                    // 此栏目下所有的媒资,并且未被此套模板添加
                    $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 1])->pluck('vasseti_id')->toArray());
                }
                // 范围过滤 template_details_id
                $query = $query->onlineStatus()->onlinePublished();
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = SubcolumnVasseti::with(['subcolumn', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
                    if (!empty($subcolumn_id) && !empty($template_details_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                        $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 1])->pluck('vasseti_id')->toArray());
                    }
                    $query = $query->onlineStatus()->onlinePublished();
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    $query = $query->onlineStatus()->onlinePublished();
                })->count();

            $data['data'] = SubcolumnVasseti::with(['subcolumn', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
                    if (!empty($subcolumn_id) && !empty($template_details_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                        $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 1])->pluck('vasseti_id')->toArray());
                    }
                    $query = $query->onlineStatus()->onlinePublished();
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    $query = $query->onlineStatus()->onlinePublished();
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        } else {
            response()->json(['content' => "非法操作!", 'status' => 'error']);
        }
    }
    return response()->json(['content' => "二级栏目参数不合法!", 'status' => 'error']);
});

/**
 * 通过二级栏目下的ID该二级栏目下的直播媒资
 */
Route::any("/subcolumns/{subcolumn_id}/vchans", function ($subcolumn_id, Request $request) {
    if (Subcolumn::find($subcolumn_id)) {
        // 1:点播媒资 2:直播媒资
        $type = 2;
        // if ($request->ajax()) {
        /**
         * 过滤字段
         */
        // 归类
        $vccat = $request->input('vccat');
        // 分类
        $vccattag = $request->input('vccattag');
        // 搜索框的值
        $search_value = $request->input('search_value');
        // // 二级栏目id
        $subcolumn_id = $request->input('subcolumn');
        // 模板相关的ID
        $template_details_id = $request->input('templateDetailsId');
        $data                = array();
        $data['draw']        = $request->get('draw');
        $start               = $request->get('start') ?: 0;
        $length              = $request->get('length') ?: 10;
        $order               = $request->get('order');
        $columns             = $request->get('columns');
        $search              = $request->get('search');

        $data['recordsTotal'] = SubcolumnVchan::whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
            if (!empty($subcolumn_id) && !empty($template_details_id)) {
                $query = $query->where('id', '=', $subcolumn_id);
                // 此栏目下所有的媒资,并且未被此套模板添加
                $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 2])->pluck('vasseti_id')->toArray());
            }
            // 范围过滤 template_details_id
            $query = $query->onlineStatus()->onlinePublished();
        })->count();
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }

        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = SubcolumnVchan::with(['subcolumn', 'vchan', 'vchan.vccattags', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccat', 'vchan.vepgs', 'vchan.vcposters'])
            ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                if (!empty($vccat)) {
                    $query = $query->where('id', $vccat);
                }
            })
            ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                if (!empty($vccattag)) {
                    $query = $query->where('vccattag_id', $vccattag);
                }
            })
            ->whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
                if (!empty($subcolumn_id) && empty($template_details_id)) {
                    $query = $query->where('id', '=', $subcolumn_id);
                    $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 2])->pluck('vasseti_id')->toArray());
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->whereHas('vchan', function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
                $query = $query->onlineStatus()->onlinePublished();
            })->count();

        $data['data'] = SubcolumnVchan::with(['subcolumn', 'vchan', 'vchan.vccattags', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccat', 'vchan.vepgs', 'vchan.vcposters'])
            ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                if (!empty($vccat)) {
                    $query = $query->where('id', $vccat);
                }
            })
            ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                if (!empty($vccattag)) {
                    $query = $query->where('vccattag_id', $vccattag);
                }
            })
            ->whereHas('subcolumn', function ($query) use ($subcolumn_id, $template_details_id) {
                if (!empty($subcolumn_id) && empty($template_details_id)) {
                    $query = $query->where('id', '=', $subcolumn_id);
                    $query = $query->whereNotIn('vasseti_id', TemplateSubcolumnVassetiData::where(['subcolumn_id' => $subcolumn_id, 'template_details_id' => $template_details_id, 'type' => 2])->pluck('vasseti_id')->toArray());
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->whereHas('vchan', function ($query) use ($search_value) {
                if (!empty($search_value)) {
                    $query->where('name', 'like', '%' . $search_value . '%')
                        ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                }
                $query = $query->onlineStatus()->onlinePublished();
            })
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    } else {
        response()->json(['content' => "非法操作!", 'status' => 'error']);
    }
    // }
    return response()->json(['content' => "二级栏目参数不合法!", 'status' => 'error']);
});

/**
 * 订单记录保存
 */
Route::any("/pricelist/store", function (Request $request) {

    // 局方名称
    $opratorName = $request->input('oprator_name');
    // 用户名非必填
    $userName = $request->input('user_name');
    // 商户编码
    $payChannel = $request->input('pay_channel');
    // 缴费类型
    $rechargeType = $request->input('recharge_type');
    // 支付终端卡号(智能卡号)
    $cardNo = $request->input('card_no');
    // 扩展字段
    $extend = $request->input('extend');
    // 订单金额
    $money = $request->input('money');
    // 用户ID
    $userId = $request->input('user_id');
    // 设备ID
    $targetId = $request->input('target_id');

    if (empty($opratorName)) {
        return response()->json(['status' => 'error', 'content' => '局方名称为空!']);
    }
    if (empty($cardNo)) {
        return response()->json(['status' => 'error', 'content' => '支付终端卡号为空!']);
    }
    if (empty($money)) {
        return response()->json(['status' => 'error', 'content' => '订单金额为空!']);
    }

    $data = [];
    if ($payChannel) {
        $data['pay_channel'] = $payChannel;
    }
    if ($rechargeType) {
        $data['recharge_type'] = $rechargeType;
    }
    if ($extend) {
        $data['extend'] = $extend;
    }

    if ($userName) {
        $data['user_name'] = $userName;
    }
    $data['card_no']   = $cardNo;
    $data['money']     = $money / 100;
    $data['target_id'] = $targetId;
    // 用户ID即设备ID
    $data['user_id']      = $userId;
    $data['oprator_name'] = $opratorName;
    $data['created_at']   = date("Y-m-d H:i:s");
    // 生成订单编号
    $orderNo          = 'DD' . date('YmdHis') . uniqid();
    $data['order_id'] = $orderNo;

    $results = DB::table('price_lists')->insert($data);
    if ($results) {
        return response()->json(['status' => 'success', 'content' => "保存成功!", 'data' => $orderNo]);
    } else {
        return response()->json(['status' => 'error', 'content' => "保存失败!"]);
    }
});

/**
 * 订单记录更新
 */
Route::any("/pricelist/update", function (Request $request) {

    // 订单编号不能为空
    $orderId = $request->input('order_id');
    if (empty($orderId)) {
        return response()->json(['status' => 'error', 'content' => "订单ID为空!"]);
    }
    // 支付平台交易流水号
    $paySeq = $request->input('pay_seq');
    if (empty($paySeq)) {
        return response()->json(['status' => 'error', 'content' => "支付平台交易流水号为空!"]);
    }
    // 支付方式
    $payment = $request->input('payment');
    if (empty($payment)) {
        return response()->json(['status' => 'error', 'content' => "支付方式为空!"]);
    }
    // 订单状态
    $orderState = $request->input('order_state');

    if (DB::table('price_lists')->whereNull('deleted_at')->where(['order_id' => $orderId])->first()) {
        $result = DB::table('price_lists')->where(['order_id' => $orderId])->update([
            'pay_seq'     => $paySeq,
            'payment'     => $payment,
            'order_state' => $orderState,
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);
        if ($result) {
            return response()->json(['status' => 'success', 'content' => "订单记录更新成功!"]);
        } else {
            return response()->json(['status' => 'error', 'content' => "订单记录更新失败!"]);
        }
    } else {
        return response()->json(['status' => 'error', 'content' => "无此订单!"]);
    }
});

// 区位图片上传
Route::post('/operation/content_templates/area/upload_img', function (Request $request) {
    // 获取图片字段
    $notices = [];
    foreach ($request->file() as $imgKey => $imgValue) {
        $image = $request->file($imgKey);
        // 如果图片不存在, 则跳过
        if (!$image) {
            return response()->json(['status' => 'error', 'content' => '没有上传图片或上传图片不存在']);
        }
        // 如果图片不合法, 则跳过
        if (!$image->isValid()) {
            return response()->json(['status' => 'error', 'content' => '上传图片不合法']);
        }
        // 允许上传的图片格式, 如果不满足, 则跳过
        $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
        if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
            return response()->json(['status' => 'error', 'content' => '上传图片格式只能是png, jpg, gif, jpeg']);
        }
        $realPath = $image->getRealPath(); //临时文件的绝对路径
        // 获得图片的扩展名
        $extension = $image->getClientOriginalExtension();
        // 重新命名上传文件名字
        $newImageName = md5(time()) . random_int(100, 999) . "." . $extension;
        // 上传图片
        $uploadConfig = config('custom.base.upload.area');
        $driver       = $uploadConfig['driver'];
        $dir          = $uploadConfig['dir'];
        $rootDir      = config('filesystems.disks.' . $driver . '.upload');
        // 图片的完整路径
        $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;
        $bool     = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
    }
    // 接受参数
    $template_type       = strtolower($request->template_type);
    $template_no         = $request->template_no;
    $area_no             = $request->area_no;
    $template_details_id = $request->template_details_id;
    $tag_no              = $request->tag_no;
    // 打包成数组
    $data = compact('template_type', 'template_no', 'area_no', 'template_details_id', 'tag_no');
    // 检测所有参数是否已经上传
    foreach ($data as $acceptKey => $acceptField) {
        if (empty($acceptField)) {
            return response()->json(['status' => 'error', 'content' => "{$acceptKey}字段没有给值"]);
        }
    }
    // 如果是区位模板5,则还需要subcolumn_id
    if ($template_type === 'area' && $template_no === '005' && $area_no === 'AREA005x1x0y0') {
        if (!$subcolumn_id = $request->subcolumn_id) {
            return response()->json(['status' => 'error', 'content' => "subcolumn_id字段没有给值"]);
        }
        $data['subcolumn_id'] = $subcolumn_id;
        // 查询数据库, 如果图片已经存在,则删除原图片,放上新图片;否则直接插入数据库
        $dbImage = DB::table('template_area_images')
            ->where(['template_details_id' => $template_details_id, 'area_no' => $area_no, 'tag_no' => $tag_no, 'subcolumn_id' => $subcolumn_id])
            ->first();
    } else {
        // 查询数据库, 如果图片已经存在,则删除原图片,放上新图片;否则直接插入数据库
        $dbImage = DB::table('template_area_images')
            ->where(['template_details_id' => $template_details_id, 'area_no' => $area_no, 'tag_no' => $tag_no])
            ->first();
    }
    $data['img'] = $fullPath;
    if ($dbImage) {
        Storage::disk($driver)->delete($dbImage->img);
        $result = DB::table('template_area_images')->where(['id' => $dbImage->id])->update($data);
    } else {
        $result = DB::table('template_area_images')->insert($data);
    }
    if ($result) {
        // $ftpConfig = config("filesystems.disks.$driver");
        // $host = $ftpConfig['host'];
        // $port = $ftpConfig['port'];
        $host   = config('custom.base.host.ftp');
        $imgUrl = "$host/$fullPath";
        return response()->json(['status' => 'success', 'content' => '图片上传成功', 'path' => $imgUrl]);
    } else {
        return response()->json(['status' => 'error', 'content' => '数据库异常']);
    }
});

/**
 * 栏目列表发布
 */
Route::get('/cms/{spid}/{termid}/collists', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $sp    = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    $data = [];
    // 获取栏目列表的数据
    $data = $dataRelease->makeCollistDatas($spid, $termid, $request->all());
    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 一级栏目发布
 */
Route::get('/cms/{spid}/{termid}/columns', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $sp    = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeColumnDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 二级栏目发布
 */
Route::get('/cms/{spid}/{termid}/subcolumns', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $sp    = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeSubcolumnDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

//Json 导入
Route::post('/data/jsonImport', function (Request $request) {
    $import_config = json_decode($request->input('import_config'),true);
    $json_data = json_decode($request->input('json_data'),true);
    if(empty($import_config) || empty($json_data)){
        return response()->json(['status' => 'error', 'content' => '参数错误']);
    }

    $res = $json_data[$import_config['row']['keyname']];

    //dd($inport_config);
    $rowsCount = count($res);
    $dataArray = [];

    //取出referto字段数据
    $referto_array = $referto_array_key = [];
    foreach ($import_config['referto'] as $val){
        $referto_array_key[] = $val['field'];
        $referto_array[$val['field']] = $val;
    }

    //取出transformer字段数据
    $transformer_array = $transformer_array_key = [];
    foreach ($import_config['transformer'] as $val){
        $transformer_array_key[] = $val['field'];
        $transformer_array[$val['field']] = $val;
    }

    //取出rowmap字段数据
    $rowmap_array = $rowmap_array_key = [];
    foreach ($import_config['rowmap'] as $val){
        $rowmap_array_key[] = $val['field'];
        $rowmap_array[$val['field']] = $val;
    }

    //处理数据
    foreach ($res as $i=>$val) {
        $data = array();
        foreach ($import_config['fields'] as $field){
            if(isset($field['value']) && !empty($field['value'])){
                $data[$field['field']] = $field['value'];
            }elseif(isset($field['keyname']) && is_array($field['keyname']) && !empty($res[$i][$field['keyname']])){
                foreach ($field['keyname'] as $k){
                    $data[$field['field']][] = $res[$i][$k];
                }
            }elseif(isset($field['keyname']) && !empty($field['keyname']) && !empty($res[$i][$field['keyname']])){
                $data[$field['field']] = $res[$i][$field['keyname']];
            }
            //referto 字段处理
            if (in_array($field['field'],$referto_array_key) && !empty($data[$field['field']])){ //如果是关联字段

                //是否多值分割符
                if(isset($field['separtor']) && !empty($field['separtor'])){
                    $data[$field['field']] = explode($field['separtor'],$data[$field['field']]);
                }
                //转换为数组处理
                if(!is_array($data[$field['field']])){
                    $data[$field['field']] = array($data[$field['field']]);
                }

                $referto_array_value = [];
                foreach ($data[$field['field']] as $j => $field_value){
                    //先查询,如果没有写入数据
                    $refer_value = DB::connection($import_config['database'])->table($referto_array[$field['field']]['table'])
                        ->where($referto_array[$field['field']]['map'], $field_value)
                        ->value($referto_array[$field['field']]['refer']);

                    if(empty($refer_value)){
                        if($referto_array[$field['field']]['pre'] == 'query'){
                            $msg  = $referto_array[$field['field']]['errorMsg'] ? $referto_array[$field['field']]['errorMsg'] : '请先导入'.$referto_array[$field['field']]['table']."数据";
                            throw new ModelNotFoundException($msg);
                        }
                        $insert_refer_data = array($referto_array[$field['field']]['map']=>$field_value);
                        $defaulFieldtValues = $field['default'];
                        foreach ($defaulFieldtValues as $k=>$defaulFieldtValue){
                            $insert_refer_data[$k] = is_array($defaulFieldtValue) ? $defaulFieldtValue[$j] : $defaulFieldtValue;
                        }
                        $refer_value = DB::connection($import_config['database'])->table($referto_array[$field['field']]['table'])
                            ->insertGetId($insert_refer_data);
                    }
                    $referto_array_value[] = $refer_value;
                }
                $data[$field['field']] = implode(",",$referto_array_value);
            }

            if (empty($data[$field['field']])){
                unset($data[$field['field']]);
            }
        }
        $dataArray[] = $data;
    }

    //成功的行数
    $successCount = 0;
    //总行数
    $rowsCount = count($dataArray);
    DB::beginTransaction();
    try {
        if ($import_config['row']['op'] == 'insert') {
            foreach ($dataArray as $data) {
                $insert_data = $data;

                foreach ($rowmap_array_key as $rowmap_field){
                    if(isset($insert_data[$rowmap_field])){
                        unset($insert_data[$rowmap_field]);
                    }
                }

                $rs = DB::connection($import_config['database'])->table($import_config['table'])->insertGetId($insert_data);
                //$rs = DB::table($inport_config->table)->insert($data);
                if ($rs) {
                    //成功的行数
                    $successCount++;
                    //rowmap字段数据写入
                    foreach ($rowmap_array as $k=>$rowmap){
                        if(!isset($data[$k]) || empty($data[$k])){
                            continue;
                        }
                        //多值字段关联数据写入
                        if(!is_array($data[$k]) && !empty($data[$k])){
                            $data[$k] = explode(",",$data[$k]);
                        }
                        $target_table_datas = array();
                        foreach ($data[$k] as $val){
                            //先查询,如果没有写入数据
                            $rowmap_value2 = DB::connection($import_config['database'])->table($rowmap['table'])
                                ->where([
                                    [$rowmap['keys'], '=', $rs],
                                    [$rowmap['rows'], '=', $val],
                                ])
                                ->value('id');

                            if(empty($rowmap_value2)){
                                $target_table_data = [];
                                $target_table_data[$rowmap['keys']] = $rs;
                                $target_table_data[$rowmap['rows']] = $val;
                                $target_table_datas[] = $target_table_data;
                            }
                        }
                        //dd($target_table_datas);
                        if(empty($target_table_datas)) continue;
                        DB::connection($import_config['database'])->table($rowmap['table'])
                            ->insert($target_table_datas);
                    }
                }
            }
        }
        elseif ($import_config['row']['op'] == 'update') {
            foreach ($dataArray as $data) {
                $where = array();
                foreach ($import_config['index'] as $index) {
                    $where[] = [$index, '=', $data[$index]];
                }
                $updata = array();
                foreach ($import_config['write'] as $up_field) {
                    $updata[$up_field] = $data[$up_field];
                }

                $rs = DB::connection($import_config['database'])->table($import_config['table'])
                    ->where($where)->update($updata);

                $ids = DB::connection($import_config['database'])->table($import_config['table'])->where($where)->pluck('id');
                //rowmap字段数据写入
                foreach ($rowmap_array as $k=>$rowmap){
                    if(!isset($data[$k]) || !in_array($k,$import_config['write']) || empty($data[$k])){
                        continue;
                    }

                    if(!is_array($data[$k])){
                        $data[$k] = explode(",",$data[$k]);
                    }

                    $target_table_datas = array();
                    //多值字段关联数据写入
                    foreach ($data[$k] as $val){
                        foreach ($ids as $id){
                            //先查询,如果没有写入数据
                            $rowmap_value2 = DB::connection($import_config['database'])->table($rowmap['table'])
                                ->where([
                                    [$rowmap['keys'], '=', $id],
                                    [$rowmap['rows'], '=', $val],
                                ])
                                ->value('id');
                            if(empty($rowmap_value2)){
                                $target_table_data = [];
                                $target_table_data[$rowmap['keys']] = $id;
                                $target_table_data[$rowmap['rows']] = $val;
                                $target_table_datas[] = $target_table_data;
                            }
                        }
                    }
                    if(empty($target_table_datas)) continue;
                    //关联表数据批量写入
                    $rs = DB::connection($import_config['database'])->table($rowmap['table'])
                        ->insert($target_table_datas);
                }

                if ($rs) {
                    //成功的行数
                    $successCount++;
                }
            }
        }
        DB::commit();
        return response()->json(['status' => 'success','content' => '导入成功']);
    }catch (\Exception $e) {
        DB::rollback(); //事务回滚
        return response()->json(['status' => 'error', 'content' => $e->getMessage()]);
    }
});


// 贵州媒资异步注入回调【消息任务处理异步反馈 和 注入CDN成功异步反馈】
Route::any('/api/ott/assets/media/import', function (Request $request) {
    // 接收回调的soap消息
    // $xmlData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
    // if (empty($xmlData)) {
    //     $xmlData = file_get_contents('php://input', true);
    // }
    Log::info($request->input());
    // Log::info($xmlData);
    $xmlData = $request->input('cmsresult');
    // 将xml转化为json对象
    $message =  simplexml_load_string($xmlData);
    if (empty($message)) {
        return response()->json(['status' => 'error', 'content' => '参数错误']);
    }
    // xml数据转json
    $result = json_encode($message);
    // json转数组
    $aResult = json_decode($result, true);

    $msgid = $aResult['msgid'];

    $injectVassetiHistory  = new InjectAssetiHistory;

    $history = $injectVassetiHistory->where('task_no','=',$msgid)->first();

    if(empty($history)){
        return response()->json(['status' => 'error', 'content' => '非法请求']);
    }
    $history = $history->toArray();

    $history['notify_content'] = $xmlData;
    // 判断异步回调类型 如果有 CmsResult 说明是 工单与海报下载处理通知
    if (isset($aResult['CmsResult'])) {
        $history['pic_state'] = !$aResult['CmsResult'] ? 1 : 0;
    }else{
        if($aResult['info']['asset_type']==3){
            $history['movie_state'] = $aResult['state']=='1' ? 1 : 0;
        }elseif($aResult['info']['asset_type']==2){
            $history['program_state'] = $aResult['state']=='1' ? 1 : 0;
        }elseif($aResult['info']['asset_type']==1){
            $history['series_state'] = $aResult['state']=='1' ? 1 : 0;
        }
    }

    $asset = Assets::where('id','=',$history['asset_id'])->first()->toArray();
    //如果是电影
    if(empty($asset['pid']) && !empty($asset['file_url'])){
        if($history['movie_state']==1 && $history['program_state']==1 && $history['series_state']==1){
            $history['task_status'] = 1;
            $ogroup_asset_id = $aResult['info']['asset_id'];
        }else{
            $history['task_status'] = 0;
        }
    }
    //如果是电视剧
    elseif(empty($asset['pid']) && empty($asset['file_url'])){
        if($history['series_state']==1 ){
            $history['task_status'] = 1;
            $ogroup_asset_id = $aResult['info']['asset_id'];
        }else{
            $history['task_status'] = 0;
        }
    }
    //如果是子集
    elseif(!empty($asset['pid']) && !empty($asset['file_url'])){
        if($history['movie_state']==1 && $history['program_state']==1 ){
            $history['task_status'] = 1;
            $ogroup_asset_id = $aResult['info']['part_id'];
        }else{
            $history['task_status'] = 0;
        }
    }

    InjectAssetiHistory::where('task_no','=',$msgid)->update($history);
    $update = array();
    if($history['task_status'] == 1){
        $update['inject_datetime'] = time();
        Assets::where('id','=',$asset['id'])->update($update);

        //更新媒资回调信息
        $stream = AssetStream::where('asset_id', $asset['id'])->first();
        if (!$stream) {
            AssetStream::create([
                'asset_id' => $asset['id'],
                'ogroup_asset_id'=>$ogroup_asset_id,
                'ogroup_asset_data'=>json_encode($aResult['info'])
            ]);
        }else{
            AssetStream::where('asset_id', $asset['id'])->update([
                'ogroup_asset_id'=>$ogroup_asset_id,
                'ogroup_asset_data'=>json_encode($aResult['info'])
            ]);
        }

    }else{
        $update['inject_datetime'] = 0;
        Assets::where('id','=',$asset['id'])->update($update);
    }
    return response()->json(['status' => 'success','content' => '成功']);

});


/*
 * 全文搜索测试部分
 */
Route::get('/search/{key}', function ($key){
    $xs = new XS(config_path('custom\search-demo.ini'));
    $search = $xs->search; // 获取 搜索对象
    $query = $key;
    $search->setQuery($query)
        ->setSort('chrono', true) //按照chrono 正序排列
        ->setLimit(20,0) // 设置搜索语句, 分页, 偏移量
    ;

    $docs = $search->search(); // 执行搜索，将搜索结果文档保存在 $docs 数组中
    $count = $search->count(); // 获取搜索结果的匹配总数估算值
    foreach ($docs as $doc){
        $subject = $search->highlight($doc->subject); // 高亮处理 subject 字段
        $message = $search->highlight($doc->message); // 高亮处理 message 字段
        echo $doc->rank() . '. ' . $subject . " [" . $doc->percent() . "%] - ";
        echo date("Y-m-d", $doc->chrono) . "<br>" . $message . "<br>";
        echo '<br>========<br>';
    }
    echo  '总数:'. $count;
});

Route::get('/makedoc/{title}/{message}', function ($title, $message){
    $xs = new XS(config_path('custom\search-demo.ini'));
    $doc = new XSDocument;
    $doc->setFields([
        'pid' => 1,
        'subject' => $title,
        'message' => $message,
        'chrono' => time(),
    ]); // 用数组进行批量赋值
    $xs->index->add($doc);
});
